package com.atguigu.study.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entities.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.concurrent.TimeUnit;
/**
* @author 阳
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2024-12-04 17:42:51
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService
{
    @Resource
    private UserMapper userMapper;
    @Resource
    private TransactionTemplate transactionTemplate;

    public String costTimeMethod()
    {
        try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
        return IdUtil.simpleUUID().substring(0,8);
    }

    @Transactional
    public int addUser(User user)
    {
        //1 某个方法超级耗时获得用户名字拼装数据
        String userName = user.getUsername()+"-"+costTimeMethod();
        user.setUsername(userName);
        //2 插入数据库成功返回
        return userMapper.insert(user);
    }




    /**
     * 优化后的方法，脑袋上没有    @Transactional注解
     * @param user
     * @return
     */
    public int addUserOptimize(User user)
    {
        //1 某个方法超级耗时获得用户名字拼装数据
        String userName = user.getUsername()+"-"+costTimeMethod();
        user.setUsername(userName);

        return transactionTemplate.execute(status -> userMapper.insert(user));
    }
}




